﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UCL;
using UCL.Forms;
using UCL.Data;

namespace DBKit5
{
    public partial class frmExcel2XmlConverter : Form
    {
        public frmExcel2XmlConverter()
        {
            InitializeComponent();
        }

        private void frmExcel2XmlConverter_Load(object sender, EventArgs e)
        {
            ButtonClickEventConfig();
        }

        private void ButtonClickEventConfig()
        {
            btnBrowserExcel.Click += new EventHandler(btn_Click);
            btnBrowserXml.Click += new EventHandler(btn_Click);
            btnParseToExcel.Click += new EventHandler(btn_Click);
            btnParseToXml.Click += new EventHandler(btn_Click);
            btnSaveExcel.Click += new EventHandler(btn_Click);
            btnSaveXml.Click += new EventHandler(btn_Click);
        }

        private void btn_Click(object sender, EventArgs e)
        {
            switch (((Button)sender).Name)
            {
                case "btnBrowserExcel":
                    this.ShowOpenFileDialog("Excel", (fn) => { tbExcelPath.Text = fn; ParseToXml(fn); });
                    break;
                case "btnBrowserXml":
                    this.ShowOpenFileDialog("Xml", (fn) => { tbXmlPath.Text = fn; ParseToExcel(fn); });
                    break;
                case "btnParseToExcel":
                    ParseToExcel(tbXmlPath.Text);
                    break;
                case "btnParseToXml":
                    ParseToXml(tbExcelPath.Text);
                    break;
                case "btnSaveExcel":
                    this.ShowSaveFileDialog("Excel", (fn) => {if(dgvExcelContent.Rows.Count==0) return "Excel内容无效"; return ((DataTable)dgvExcelContent.DataSource).SaveToExcel(fn); });
                    break;
                case "btnSaveXml":
                    this.ShowSaveFileDialog("Xml", (fn) => { if (wbXmlContent.Tag==null) return "Xml内容无效"; FileHelper.SaveAsFile(wbXmlContent.Tag.ToString(), fn); return "success"; });
                    break;
            }
        }

        private void ParseToXml(string xlsPath)
        {
            if (xlsPath.Length == 0) return;
            XMLHelper xh = new XMLHelper();
            xh.LoadExcelDataTable(new ExcelHelper(xlsPath).ExecuteDataTable());
            string filepath = string.Format("{0}\\ADFS\\DBKit\\Temp\\tmpDBKit{1}.xml", Application.StartupPath, DateTime.Now.ToString("yyyyMMddHHmmss"));
            FileHelper.SaveAsFile(xh.Document.InnerXml, filepath);
            wbXmlContent.Url = new Uri(filepath);
            wbXmlContent.Tag = xh.Document.InnerXml;

        }
        private void ParseToExcel(string xmlPath)
        {
            if (xmlPath.Length == 0) return;
            dgvExcelContent.DataSource = new XMLHelper(xmlPath).ConvertToExcelDataTable();
        }
    }
}
